package cn.wolfcode.elasticjob;

import cn.wolfcode.anno.CustomJob;
import cn.wolfcode.constant.JobStrategy;
import cn.wolfcode.domain.FileCustom;
import cn.wolfcode.mapper.FileCustomRepository;
import cn.wolfcode.util.BaseSimpleJob;
import com.dangdang.ddframe.job.api.ShardingContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@CustomJob(cron="0/5 * * * * ?",
        shardingTotalCount = 4,
        shardingItemParameters="0=text,1=image,2=radio,3=vedio",
        jobStrategy = JobStrategy.SIMPLE)
@Slf4j
public class MySimpleElasticJob extends BaseSimpleJob {

    @Autowired
    private FileCustomRepository fileCustomRepository;

    @Override
    public void execute(ShardingContext shardingContext) {
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String fileType){
        List<FileCustom> fileList = fileCustomRepository.selecByType(fileType);
        for(FileCustom fileCustom:fileList){
            backUpFile(fileCustom);
        }
    }
    private void backUpFile(FileCustom fileCustom){
        try {
            //模拟备份动作
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info(Thread.currentThread().getName()+"执行文件备份====>"+fileCustom);
        fileCustomRepository.changeState(fileCustom.getId(),1);
    }
}
